<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区  用户的数据 -->
    <el-card>
      <!-- 搜索区域 -->

      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- table表格 -->
      <tree-table
        class="treeTable"
        :data="catelist"
        show-row-hover
        :columns="columns"
        :selection-type="false"
        show-index
        :expand-type="false"
        
        index-text="#"
        border
      >
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            style="color: lightgreen"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序等级 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作的作用域卡槽 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCate(scope.row.cat_id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletCate(scope.row.cat_id)"></el-button>
        </template>
      </tree-table>

      <!-- 分页功能 size-change改变事件 -->
      <el-pagination
        class="page"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[5, 8, 10, 13]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name" ></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options 用来指定数据源 -->
          <!-- props用来指定配置对象 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parenthandleChange"
            clearable
            
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改类名 -->
      <el-dialog
      title="修改类名"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateCli">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类的数据列表
      catelist: [],
      //总数据条数
      total: 0,
      //table树形表格指定列
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          //表示当前这一列定义为模板列
          type: "template",
          //表示当前这一列使用的模板名称
          template: "isOk",
        },
        {
          label: "排序",
          //表示当前这一列定义为模板列
          type: "template",
          //表示当前这一列使用的模板名称
          template: "order",
        },
        {
          label: "操作",
          //表示当前这一列定义为模板列
          type: "template",
          //表示当前这一列使用的模板名称
          template: "opt",
        },
      ],
      //控制分类对话框显示
      addCateDialogVisible: false,
      editCateDialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        //添加分类的名称
        cat_name: "",
        //父类的ID
        cat_pid: 0,
        //当前分类等级
        cat_level: 0,
      },
      addCateFormRules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
      },
       editCateForm: {
        //添加分类的名称
        cat_name: "",
        //每个类的id
        cat_id: 0,
      },
       editCateFormRules: {
        cat_name: [
          {
            required: true,
            message: "请输入修改的类名",
            trigger: "blur",
          },
        ],
      },
      //存放添加时获取到的父级数据
      parentCateList: [],
      //指定级联选择器的配置对象
      cascaderProps: {
        checkStrictly: true,
        value:'cat_id',
        label:'cat_name',
        children:'children'
      },
      //选中的分类的ID
      selectedKeys:[],
      
    };
  },

  created() {
    this.getCateList();
  },

  computed: {},

  methods: {
   
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.querInfo,
      });

      if (res.meta.status !== 200) {
        return this.$message.error("数据加载失败");
      }
      //数据赋值给catelist
      console.log(res.data.result)
      this.catelist = res.data.result;
      //为总条数赋值
      this.total = res.data.total;
    },
    //监听pagesize改变
    handleSizeChange(newSize) {
      this.querInfo.pagesize = newSize;
      this.getCateList();
    },
    //监听pagenum 改变
    handleCurrentChange(newPage) {
      this.querInfo.pagenum = newPage;
      this.getCateList();
    },
    //添加分类按钮
    showAddCateDialog() {
      //先获取父级数据分类的数据列表
      this.getParentCatelist();

      this.addCateDialogVisible = true;
    },
    //获取父级数据分类的数据列表
    async getParentCatelist() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });

      if (res.meta.status !== 200) {
        return this.$message.error("获取父级数据失败");
      }
      
      this.parentCateList = res.data;
    },
   
    //对话框确定按钮，添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async valid =>{
        if(!valid) return 
       const {data:res} = await this.$http.post('categories',this.addCateForm)

        if(res.meta.status !==201){
          return this.$message.error('添加失败')
        }

        this.$message.success('添加分类成功！')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    //选择项改变触发
    parenthandleChange(){
      //如果selectedKeys数组中的id大于零，说明选择的父级分类
      if(this.selectedKeys.length>0){
        //获取父级ID
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length-1]
        //获取当前等级
        this.addCateForm.cat_level = this.selectedKeys.length
        
        return 
      } else{
          this.addCateForm.cat_pid = 0
          this.addCateForm.cat_level = 0
          
      }
    },
     //关闭对话框清空值
    addCateDialogClosed() {
      this.selectedKeys = [];
      this.$refs.addCateFormRef.resetFields();
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    //编辑类名的对话框
    editCate(id){
      //获取当前类的ID
      this.editCateForm.cat_id = id

      this.editCateDialogVisible = true
    },
    //确定按钮，修改类名
    editCateCli(){
      this.$refs.editCateFormRef.validate(async valid=>{
        if(!valid) return

        const {data: res} = await this.$http.put(`categories/${this.editCateForm.cat_id}`,this.editCateForm)

        if(res.meta.status !==200) {
          return this.$message.error('修改失败')
        }

        this.$message.success("修改成功")
        this.getCateList()
        this.editCateDialogVisible = false
      })
    },
    async deletCate(id){
    
      const confirmResult = await this.$confirm("是否删除该类?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err); //处理报错

      //点击确定confirmResult打印出confirm
      //点击取消confirmResult打印出cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      }
      //删除用户
      const { data: res } = await this.$http.delete("categories/" + id);

      if (res.meta.status !== 200) {
        this.$message.success("删除失败");
      }
      this.$message.success("删除成功");
      this.getCateList()
    },
 
    editCateDialogClosed(){
        this.$refs.editCateFormRef.resetFields();
    }
  },
};
</script>
<style lang='css' scoped>
.treeTable {
  margin-top: 15px;
}
.page {
  margin-top: 15px;
}
.el-cascader{
  width: 100%;
}
</style>